<?php

Yii::import('application.mlm.core.mlm_function');
Yii::import('application.mlm.core.binary.*');
Yii::import('application.mlm.core.matrix.*');
Yii::import('application.mlm.core.board.*');

class BinaryController extends MemberController {

    //sponsoring
    public function actionSponsoring() {
        $ref = function_lib::uri_segment(4);
        if ((!empty($ref) || function_lib::get_network_id($ref != '')) && (function_lib::get_network_id($ref) >= Yii::app()->user->getState('network_id'))) {
            $sponsor_id = function_lib::get_network_id(function_lib::uri_segment(4));
        } else {
            $sponsor_id = Yii::app()->user->getState('network_id');
        }
        $up_sponsor_id = function_lib::get_network_sponsor_network_id($sponsor_id);
        $level = function_lib::get_level_depth($sponsor_id, Yii::app()->user->getState('network_id'));
        $top_data = sys_network::model()->with('rel_network_to_member')->find('network_id=:id', array(':id' => $sponsor_id));

        $rs_data = vo_network::get_member_data($sponsor_id);

        $this->render('sponsoring', array(
            'top_data' => $top_data,
            'sponsor_id' => $sponsor_id,
            'up_sponsor_id' => $up_sponsor_id,
            'level' => $level,
            'rs_data' => $rs_data,
        ));
    }

    //report log
    public function actionReport() {
        //$summary['wait_left'] = vo_network::get_last_wait_node(Yii::app()->user->getState('network_id'), 'left');
        //$summary['wait_right'] = vo_network::get_last_wait_node(Yii::app()->user->getState('network_id'), 'right');
        //$summary['total_node_left'] = function_lib::get_one("network_total_node_left", "sys_network", "network_id = '" . Yii::app()->user->getState('network_id') . "'");
        //$summary['total_node_right'] = function_lib::get_one("network_total_node_right", "sys_network", "network_id = '" . Yii::app()->user->getState('network_id') . "'");
        //$summary['total_match'] = function_lib::get_one("SUM(netgrow_master_match)", "sys_netgrow_master", "netgrow_master_network_id = '" . Yii::app()->user->getState('network_id') . "'");
        //$summary['total_sponsor'] = function_lib::get_one("COUNT(*)", "sys_network", "network_sponsor_network_id = '" . Yii::app()->user->getState('network_id') . "'");
        //$summary['total_flushout'] = function_lib::get_one("COUNT(*)", "sys_netgrow_master", "netgrow_master_network_id = '" . Yii::app()->user->getState('network_id') . "' AND netgrow_master_match >= 12");
        $summary['wait_left'] = vo_network::get_last_wait_node_bonus(Yii::app()->user->getState('network_id'), 'left');
        $summary['wait_right'] = vo_network::get_last_wait_node_bonus(Yii::app()->user->getState('network_id'), 'right');
        $summary['total_node_left'] = function_lib::get_one("SUM(netgrow_bonus_node_left)", "sys_netgrow_bonus", "netgrow_bonus_network_id = '" . Yii::app()->user->getState('network_id') . "'");
        $summary['total_node_right'] = function_lib::get_one("SUM(netgrow_bonus_node_right)", "sys_netgrow_bonus", "netgrow_bonus_network_id = '" . Yii::app()->user->getState('network_id') . "'");
        $summary['total_match'] = function_lib::get_one("SUM(netgrow_bonus_match)", "sys_netgrow_bonus", "netgrow_bonus_network_id = '" . Yii::app()->user->getState('network_id') . "'");
        $summary['total_sponsor'] = function_lib::get_one("SUM(sponsor_netgrow_value)", "sp_sponsor_netgrow", "sponsor_netgrow_network_id = '" . Yii::app()->user->getState('network_id') . "'");
        $summary['total_flushout'] = function_lib::get_one("COUNT(*)", "sys_netgrow_bonus", "netgrow_bonus_network_id = '" . Yii::app()->user->getState('network_id') . "' AND netgrow_bonus_match >= 12");

        $date_start_default = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        //$date_end_default = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));
        $date_end_default = date("Y-m-d");

        $date_start = (!empty($_POST['date_start'])) ? $_POST['date_start'] : $date_start_default;
        $date_end = (!empty($_POST['date_end'])) ? $_POST['date_end'] : $date_end_default;

        //$data = vo_network::get_netgrow_master(Yii::app()->user->getState('network_id'), $date_start, $date_end);
        $data = vo_network::get_netgrow_bonus(Yii::app()->user->getState('network_id'), $date_start, $date_end);

        $this->render('report', array(
            'summary' => $summary,
            'data' => $data,
            'date_start' => $date_start,
            'date_end' => $date_end,
        ));
    }
    
    public function actionReward(){
        $summary['left'] = vo_network::get_data_reward(Yii::app()->user->getState('network_id'),"L");
        $summary['right'] = vo_network::get_data_reward(Yii::app()->user->getState('network_id'),"R");
        
        //qord
        $summary_qord['left'] = vo_network::get_data_reward_qord(Yii::app()->user->getState('network_id'),"L");
        $summary_qord['right'] = vo_network::get_data_reward_qord(Yii::app()->user->getState('network_id'),"R");
        //haji
        $summary_haji['left'] = vo_network::get_data_reward_haji(Yii::app()->user->getState('network_id'),"L");
        $summary_haji['right'] = vo_network::get_data_reward_haji(Yii::app()->user->getState('network_id'),"R");
        //am hasanah
        $summary_wqhd['left'] = vo_network::get_data_reward_wqhd(Yii::app()->user->getState('network_id'),"L");
        $summary_wqhd['right'] = vo_network::get_data_reward_wqhd(Yii::app()->user->getState('network_id'),"R");
        
        
        $this->render('reward', array(
            'summary' => $summary,
            'summary_qord' => $summary_qord,
            'summary_haji' => $summary_haji,
            'summary_wqhd' => $summary_wqhd,
            'data' => $data,
        ));
    }

    //geneology
    public function actionGeneology() {
        Yii::import('application.mlm.core.mlm_function');

        if (isset($_POST['network_mid'])) {
            $check_uplink = mlm_function::check_uplink($_POST['network_mid'], Yii::app()->user->getState('network_mid'));

            if ($check_uplink == 'T') {
                $top_id = function_lib::get_network_id($_POST['network_mid']);
            } else {
                $top_id = Yii::app()->user->getState('network_id');
                $message = '<div style="margin-bottom:5px;">ID Member yang anda masukkan bukan jaringan anda.</div>';
            }
        } else {
            $top_mid = function_lib::uri_segment(4);
            $top_id_check_uplink = mlm_function::check_uplink($top_mid, Yii::app()->user->getState('network_mid'));
            //$top_id = ((!empty($top_mid) && (function_lib::get_network_id($top_mid) >= Yii::app()->user->getState('network_id')))) ? function_lib::get_network_id($top_mid) : Yii::app()->user->getState('network_id');
            $top_id = ((!empty($top_mid) && ($top_id_check_uplink == 'T'))) ? function_lib::get_network_id($top_mid) : Yii::app()->user->getState('network_id');
        }

        $data = function_lib::generate_geneology_binary($top_id, 3);

        for ($i = 1; $i <= 15; $i++) {
            if (isset($data[$i]['network_level_status']) && $data[$i]['network_level_status'] != '') {
                $data[$i]['box_class'] = 'box-' . $data[$i]['network_level_status'];
            } else {
                $data[$i]['box_class'] = 'box';
            }
        }

        $this->render('geneology_3_level', array(
            'top_id' => $top_id,
            'data' => $data,
        ));
    }

    //upgrade level status
    public function actionUpgrade() {
        $model = new captcha_form;

        if (isset($_POST['captcha_form'])) {
            $model->attributes = $_POST['captcha_form'];

            Yii::app()->user->setFlash('upgrade_serial_part1', $_POST['upgrade_serial'][1]);
            Yii::app()->user->setFlash('upgrade_serial_part2', $_POST['upgrade_serial'][2]);
            Yii::app()->user->setFlash('upgrade_serial_part3', $_POST['upgrade_serial'][3]);
            Yii::app()->user->setFlash('upgrade_serial_part4', $_POST['upgrade_serial'][4]);
            $pin_validation = vo_network::pin_validation(Yii::app()->user->getId(), $_POST['pin']);

            if (!$pin_validation) {
                Yii::app()->user->setFlash('error', 'Maaf, PIN yang anda masukkan belum benar.');
            } elseif (!$model->validate()) {
                Yii::app()->user->setFlash('error', 'Maaf, Kode Unik yang anda masukkan belum benar.');
            } else {
                $serial_id = $_POST['upgrade_serial'][1] . $_POST['upgrade_serial'][2] . $_POST['upgrade_serial'][3] . $_POST['upgrade_serial'][4];
                $pin = $_POST['upgrade_pin'];

                $serial_products = vo_ecommerce::serial_products_validation($serial_id, $pin);
                $serial_products_category_prefix = vo_ecommerce::get_products_category_prefix($serial_products['serial_products_products_category_id']);

                if ($serial_products == false) {
                    Yii::app()->user->setFlash('error', 'Maaf, Nomor Serial atau PIN Upgrade yang anda masukkan belum benar.');
                } elseif ($serial_products['serial_products_is_active'] == '0') {
                    Yii::app()->user->setFlash('error', 'Maaf, Status Serial Upgrade yang anda masukkan pasif dan belum bisa digunakan.');
                } elseif ($serial_products['serial_products_is_used'] == '1') {
                    Yii::app()->user->setFlash('error', 'Maaf, Serial Upgrade yang anda masukkan sudah digunakan.');
                } else {
                    //check level status upgrade
                    $arr_products_category_prefix = array();
                    $arr_products_category_prefix[0] = '';
                    $arr_products_category_prefix[1] = 'DIST';
                    $arr_products_category_prefix[2] = 'WARE';
                    $arr_products_category_prefix[3] = 'WHUM';
                    $arr_products_category_prefix[4] = 'WHQD';
                    $arr_products_category_prefix[5] = 'FACT';
                    $arr_products_category_prefix[6] = 'EDUC';
                    $arr_products_category_prefix[7] = 'UMRH';
                    $arr_products_category_prefix[8] = 'ELHJ';
                    $arr_products_category_prefix[9] = 'FPRO';
                    $arr_products_category_prefix[10] = 'UMHJ';
                    $arr_products_category_prefix[11] = 'PLUS';
                    $arr_products_category_prefix[12] = 'QORD';
                    $arr_products_category_prefix[13] = 'QKPR';                    

                    $arr_level_status = array();
                    $arr_level_status[0] = 'passive';
                    $arr_level_status[1] = 'distributor';
                    $arr_level_status[2] = 'warehouse';
                    $arr_level_status[3] = 'warehouse';
                    $arr_level_status[4] = 'warehouse';
                    $arr_level_status[5] = 'factory';
                    $arr_level_status[6] = 'factory';
                    $arr_level_status[7] = 'factory';
                    $arr_level_status[8] = 'factory';
                    $arr_level_status[9] = 'factory';
                    $arr_level_status[10] = 'factory';
                    $arr_level_status[11] = 'factory';
                    $arr_level_status[12] = 'factory';
                    $arr_level_status[13] = 'factory';
                    

                    $old_network_level_status = array_search(function_lib::get_network_level_status(Yii::app()->user->getState('network_id')), $arr_level_status);
                    $new_network_level_status = array_search($serial_products_category_prefix, $arr_products_category_prefix);

                    if ($new_network_level_status > $old_network_level_status) {
                        //proses upgrade
                        $current_type = $arr_level_status[$old_network_level_status];
                        $upgrade_type = $arr_level_status[$new_network_level_status];
                        $network_id = Yii::app()->user->getState('network_id');
                        $network_mid = Yii::app()->user->getState('network_mid');
                        $sponsor_network_id = Yii::app()->user->getState('network_sponsor_network_id');
                        $upline_network_id = Yii::app()->user->getState('network_upline_network_id');
                        $today = date("Y-m-d");
                        $datetime = date("Y-m-d H:i:s");

                        $mlm_matrix = new mlm_matrix();
                        $sponsor = new mlm_sponsor;
                        $sponsor->add_sponsor_depend('gen_node_extra');
                        $match_bonus = new mlm_match_gi();
                        $match_bonus->add_pasangan_depend('gen_match');
                        $match_bonus->add_pasangan_depend('match');
                        $match_bonus->set_flushout(12);
                        $board = new mlm_board;

                        /*
                         * WAWAN 6-1-2012
                         * Penambahan bonus Direct Royalti produk
                         * bonus sponsor upgrade warehous dihilangkan diganti bonus direct royalti
                         */

                        //Instance class
                        $sponsor_upgrade = new mlm_sponsor_upgrade;

                        //Cari bonus value-nya dari produk yang dipilih untuk upgrade
                        //produk id
                        $product_id = function_lib::get_one("serial_products_buyer_products_id", "sys_serial_products_buyer", "serial_products_buyer_serial_products_id = '" . $serial_id . "' ");
                        $bonus_value = function_lib::get_one("products_sponsor_bonus_value", "ecom_products", "products_id = '" . $product_id . "' ");

                        /*
                         * Eof Penambahan direct rouyalti produk (sponsor upgrade)
                         */

                        switch ($upgrade_type) {
                            case "distributor":
                                //upgrade distributor
                                $sponsor->set_date($today)->gen_node($sponsor_network_id);
                                $mlm_matrix->set_date($today)
                                        ->set_height(10)
                                        ->set_width(4)
                                        ->set_network_id($network_id)->set_network_mid($network_mid)->insert_node();
                                break;

                            case "warehouse":
                                //upgrade warehouse
                                if ($current_type == 'passive') {


                                    $sponsor->set_date($today)
                                            ->gen_node($sponsor_network_id);



                                    $mlm_matrix->set_date($today)
                                            ->set_height(10)
                                            ->set_width(4)
                                            ->set_network_id($network_id)->set_network_mid($network_mid)->insert_node();
                                }

                                /*
                                 * Penambahan aksinya disini
                                 * 1. disable dulu bonus sponsornya
                                 * 2. aktifkan bonus sponsor_upgradenya
                                 */
//                                $sponsor->set_sponsor(function_lib::get_network_mid($sponsor_network_id))
//                                        ->set_date($today)
//                                        ->execute();
                                if ($serial_products_category_prefix == "WHUM" || $serial_products_category_prefix == "WHQD") {
                                    $sponsor_upgrade->set_sponsor(function_lib::get_network_mid($sponsor_network_id))
                                            ->add_sponsor_depend('gen_node_extra_warehouse')
                                            ->set_date($today)
                                            ->set_sponsored_id($network_id)
                                            ->set_bonus_value($bonus_value)
                                            ->execute();
                                } else {
                                    $sponsor_upgrade->set_sponsor(function_lib::get_network_mid($sponsor_network_id))
                                            ->set_date($today)
                                            ->set_sponsored_id($network_id)
                                            ->set_bonus_value($bonus_value)
                                            ->execute();
                                }
                                $match_bonus->set_date($today)->set_flushout(12);
                                $match_bonus->insert_netgrow_bonus($network_id, $upline_network_id, $today, 1);
                                $match_bonus->execute();
                                break;

                            case "factory":

                                //jika upgrade dari umroh ke haji hanya menghasilkan bonus sponsor
                                if ($serial_products_category_prefix == "UMHJ") {
                                    //hanya bisa dipakai dari paket umroh
                                    $check_last_upgrade = function_lib::get_one("serial_products_user_serial_products_id", "sys_serial_products_user", "serial_products_user_network_id = '$network_id' ORDER BY serial_products_user_id DESC");
                                    $last_status_membership = substr($check_last_upgrade, 0, 4);

                                    if (strtoupper($last_status_membership) == "FACT") {
                                        $sponsor->set_sponsor(function_lib::get_network_mid($sponsor_network_id))->set_date($today)->execute_umhj();
                                    } else {
                                        Yii::app()->user->setFlash('error', 'Proses Upgrade Membership Gagal diproses. Serial ini hanya bisa dipakai untuk Upgrade dari program Umroh ke Program Haji');
                                        $this->redirect('upgrade');
                                    }
                                } else {
                                    //upgrade factory
                                    if ($current_type == 'passive') {
                                        $sponsor->set_date($today)->gen_node($sponsor_network_id);
                                        $mlm_matrix->set_date($today)
                                                ->set_height(10)
                                                ->set_width(4)
                                                ->set_network_id($network_id)->set_network_mid($network_mid)->insert_node();

                                        //menghasilkan bonus pasangan
                                        $match_bonus->set_date($today)->set_flushout(12);
                                        $match_bonus->insert_netgrow_bonus($network_id, $upline_network_id, $today, 1);
                                        $match_bonus->execute();
                                    } elseif ($current_type == 'distributor') {
                                        $match_bonus->set_date($today)->set_flushout(12);
                                        $match_bonus->insert_netgrow_bonus($network_id, $upline_network_id, $today, 1);
                                        $match_bonus->execute();
                                    }
                                    /*
                                     * wawan 16-01-2012 23:47
                                     * Perubahan skema sponsor untuk factory
                                     * 1. paket produk tidak mendapatkan bonus sponsor, tapi mendapatkan royalti produk
                                     * 2. paket edukasi dan umroh mendapatkan bonus sponsor 500.000
                                     * 3. paket haji dapat bonus sponsor 1.000.000
                                     * 
                                     */

                                    // SEBELUM DIAKTIFKAN HAPUS DULU BARIS DIATAS

                                    if ($serial_products_category_prefix == "EDUC" || $serial_products_category_prefix == "FACT" || $serial_products_category_prefix == "QORD") {

                                        $sponsor->set_sponsor(function_lib::get_network_mid($sponsor_network_id))->set_date($today)->execute();
                                    } elseif ($serial_products_category_prefix == "ELHJ" || $serial_products_category_prefix == "QKPR") {

                                        $sponsor->set_sponsor(function_lib::get_network_mid($sponsor_network_id))->set_date($today)->execute_haji();
                                    } elseif ($serial_products_category_prefix == "FPRO") {

                                        $sponsor_upgrade->set_sponsor(function_lib::get_network_mid($sponsor_network_id))
                                                ->add_sponsor_depend('gen_node_extra')
                                                ->set_date($today)
                                                ->set_sponsored_id($network_id)
                                                ->set_bonus_value($bonus_value)
                                                ->execute();
                                    } elseif ($serial_products_category_prefix == "PLUS") {

                                        $sponsor->set_sponsor(function_lib::get_network_mid($sponsor_network_id))->set_date($today)->execute_plus();
                                    }

                                    //selain UMHJ masuk board
                                    $new_board_network_mid = $board->generate_mid($network_id, '1');
                                    Yii::app()->db->createCommand("INSERT INTO sys_board_network SET board_network_member_id = '" . $network_id . "',
                                                                board_network_network_mid = '" . $new_board_network_mid . "',
                                                                board_network_board_class = '1'")->execute();
                                    $manager_network_id = Yii::app()->db->getLastInsertID();
                                    $board->input_board($manager_network_id, $today, '1');
                                }

                                break;
                        }

                        //ubah level status
                        Yii::app()->db->createCommand("UPDATE sys_network SET network_level_status = '" . $arr_level_status[$new_network_level_status] . "' WHERE network_id = '" . $network_id . "'")->execute();

                        //masukkan ke log level status
                        Yii::app()->db->createCommand("INSERT INTO sys_network_level_status_log SET network_level_status_log_network_id = '" . $network_id . "', network_level_status_log_value = '" . $arr_level_status[$new_network_level_status] . "', network_level_status_log_datetime = '" . $datetime . "'")->execute();

                        //update titik level status ke jaringan
                        mlm_function::update_network_level_status($network_id, $upline_network_id, $arr_level_status[$old_network_level_status], $arr_level_status[$new_network_level_status]);

                        //ubah status serial
                        Yii::app()->db->createCommand("UPDATE sys_serial_products SET serial_products_is_used = '1' WHERE serial_products_id = '" . $serial_id . "'")->execute();

                        //masukkan log pengguna serial produk
                        Yii::app()->db->createCommand("INSERT INTO sys_serial_products_user SET serial_products_user_serial_products_id = '" . $serial_id . "', serial_products_user_network_id = '" . $network_id . "', serial_products_user_datetime = '" . $datetime . "'")->execute();

                        Yii::app()->user->setFlash('success', 'Proses Upgrade Membership berhasil diproses.');
                    } else {
                        //pesan error bahwa paket upgrade lebih rendah daripada paket terakhir member
                        Yii::app()->user->setFlash('error', 'Proses Upgrade gagal diproses. Paket ID Member ' . Yii::app()->user->getState('network_mid') . ' saat ini adalah ' . ucfirst(function_lib::get_network_level_status(Yii::app()->user->getState('network_id'))) . '.');
                    }
                }
            }
            $this->redirect('upgrade');
        }

        $this->render('upgrade', array(
            'model' => $model,
        ));
    }

    public function actionLog_level_status() {
        $date_start_default = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $date_end_default = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));

        $date_start = (!empty($_POST['date_start'])) ? $_POST['date_start'] : $date_start_default;
        $date_end = (!empty($_POST['date_end'])) ? $_POST['date_end'] : $date_end_default;

        $date_diff = ((strtotime($date_end) - strtotime($date_start)) / 86400) + 1;
        $network_id = Yii::app()->user->getState('network_id');

        $data = array();

        for ($i = 0; $i < $date_diff; $i++) {
            $arr_date = explode("-", $date_start);
            $date = date("Y-m-d", mktime(0, 0, 0, $arr_date[1], $arr_date[2] + $i, $arr_date[0]));

            $sql_level_status = "SELECT * FROM sys_netgrow_level_status WHERE netgrow_level_status_network_id = '" . $network_id . "' AND netgrow_level_status_date = '" . $date . "'";
            $rs_level_status = Yii::app()->db->createCommand($sql_level_status)->queryAll();

            if ($rs_level_status != false) {

                $data[$i]['date'] = $date;
                $data[$i]['passive_L'] = 0;
                $data[$i]['distributor_L'] = 0;
                $data[$i]['warehouse_L'] = 0;
                $data[$i]['factory_L'] = 0;
                $data[$i]['passive_R'] = 0;
                $data[$i]['distributor_R'] = 0;
                $data[$i]['warehouse_R'] = 0;
                $data[$i]['factory_R'] = 0;

                foreach ($rs_level_status as $row_level_status) {
                    $data[$i][$row_level_status['netgrow_level_status_level'] . '_' . $row_level_status['netgrow_level_status_position']] = $row_level_status['netgrow_level_status_value'];
                }
            }
        }

        $this->render('log_level_status', array(
            'date_start' => $date_start,
            'date_end' => $date_end,
            'date_diff' => $date_diff,
            'data' => $data,
        ));
    }

}
